/**
 * 
 */
package net.loyintean.pearlshell.logcenter.jms.activemq;

import java.util.ArrayList;
import java.util.List;
//import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import net.loyintean.pearlshell.logcenter.jms.IJmsSender;
import net.loyintean.pearlshell.logcenter.jms.IJmsSenderFactory;
import net.loyintean.pearlshell.logcenter.jms.impl.JmsSenderImpl;
import net.loyintean.pearlshell.logcenter.model.IConfigModel;

/**
 * @author Administrator
 * 
 */
public class MultiJmsSenderFacotryImpl extends IJmsSenderFactory {

	private List<IJmsSender> senderList = new ArrayList<IJmsSender>();

	// private Random random = new Random(System.currentTimeMillis());

	private AtomicInteger currentSenderIndex = new AtomicInteger(0);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.loyintean.pearlshell.logcenter.jms.impl.IJmsSenderFactory#create(com
	 * .sinosig.pearlshell.logcenter.model.IConfigModel)
	 */
	@Override
	public IJmsSender create(IConfigModel config) {

		if (senderList.isEmpty()) {
			init();
		}

		return chooseOne();
	}

	private void init() {
		ConnectionFactory factory = new ActiveMQConnectionFactory(
				ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");

		JmsSenderImpl sender = new JmsSenderImpl();
		sender.init(factory, "loyMQ");
		senderList.add(sender);

		sender = new JmsSenderImpl();
		sender.init(factory, "loyMQ_1");
		senderList.add(sender);

		sender = new JmsSenderImpl();
		sender.init(factory, "loyMQ_2");
		senderList.add(sender);

	}

	private IJmsSender chooseOne() {
		int index = // random.nextInt(senderList.size());
		currentSenderIndex.addAndGet(1);

		return senderList.get(index % senderList.size());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.loyintean.pearlshell.logcenter.jms.impl.IJmsSenderFactory#create(java
	 * .lang.String, java.lang.String)
	 */
	@Override
	@Deprecated
	public IJmsSender create(String url, String destinationName) {
		return null;
	}

}
